<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="订单号" prop="orderNumber">
        <el-input v-model="queryParams.orderNumber" placeholder="请输入订单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="单据日期" prop="billData">
        <el-date-picker clearable v-model="queryParams.billData" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择单据日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户订单号" prop="clientOrderNumber">
        <el-input v-model="queryParams.clientOrderNumber" placeholder="请输入客户订单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户下单日期" prop="clinentOrderDate">
        <el-date-picker clearable v-model="queryParams.clinentOrderDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择客户下单日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="计划开工时间" prop="scheduledStartTime">
        <el-date-picker clearable v-model="queryParams.scheduledStartTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择计划开工时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核状态" prop="audit">
        <el-select v-model="queryParams.audit" placeholder="请选择审核状态" clearable>
          <el-option v-for="dict in dict.type.audit" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="结案状态" prop="close">
        <el-select v-model="queryParams.close" placeholder="请选择结案状态" clearable>
          <el-option v-for="dict in dict.type.close" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="计划完工时间" prop="pctime">
        <el-date-picker clearable v-model="queryParams.pctime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择计划完工时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户型号" prop="customerModel">
        <el-select v-model="queryParams.customerModel" placeholder="请选择审核状态" clearable>
          <el-option v-for="dict in dict.type.customer_model" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售订单号" prop="clientOrderNumber" label-width="85px">
        <el-input v-model="queryParams.clientOrderNumber" placeholder="请输入销售订单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="颜色" prop="colour">
        <el-select v-model="queryParams.colour" filterable placeholder="请选择颜色" clearable>
          <el-option v-for="dict in dict.type.colour" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <CustomSearch ref="ClientSelect2" label="客户名称" prop="clientName" labelWidth="110px" :tableKeys="ClientTableKeys2"
        formTitle="选择客户" primaryKey="clientName" showField="clientName" @getSearchList="getlistClient2"
        @updateQueryParams="updateQueryParamsForClient2" @selectDialogItem="selectDialogItemForClient2"></CustomSearch>
      <CustomSearch ref="ProductSelect2" label="产品" prop="productId" labelWidth="50px" :tableKeys="ProductTableKeys2"
        formTitle="选择产品" primaryKey="productId" showField="productName" @getSearchList="getlistProduct2"
        @updateQueryParams="updateQueryParamsForProduct2" @selectDialogItem="selectDialogItemForProduct2"
        style="width=100px">
      </CustomSearch>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['storage:tickets:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['storage:tickets:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['storage:tickets:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['storage:tickets:add']">同步</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="audit" plain size="mini" :disabled="single" @click="handleAudit"
          v-hasPermi="['storage:tickets:audit']">审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="close" plain size="mini" :disabled="single" @click="handleClose"
          v-hasPermi="['storage:tickets:close ']">结案</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="close" plain size="mini" :disabled="multiple" @click="distributionInfo"
          v-hasPermi="['storage:tickets:remove']">分配产品线</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="stamp" plain size="mini" :disabled="single" @click="turngenerate()"
          v-hasPermi="['storage:tickets:print']">打印车辆ID</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['storage:tickets:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ticketsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单编号" align="center" prop="ticketsId" />
      <el-table-column label="订单号" align="center" prop="orderNumber" />
      <el-table-column label="单据日期" align="center" prop="billData" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.billData, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="clientName" />
      <el-table-column label="客户订单号" align="center" prop="clientOrderNumber" />
      <el-table-column label="客户下单日期" align="center" prop="clinentOrderDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.clinentOrderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品编码" align="center" prop="productId" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="specifications">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.specification_and_model" :value="scope.row.specifications" />
        </template>
      </el-table-column>
      <el-table-column label="客户型号" align="center" prop="customerModel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_model" :value="scope.row.customerModel" />
        </template>
      </el-table-column>
      <el-table-column label="外箱尺寸" align="center" prop="cartonSize">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.carton_size" :value="scope.row.cartonSize" />
        </template>
      </el-table-column>
      <el-table-column label="颜色" align="center" prop="color">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.colour" :value="scope.row.colour" />
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="warehouseId" />
      <el-table-column label="产品线" align="center" prop="productLine">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_line" :value="scope.row.productLine" />
        </template>
      </el-table-column>
      <el-table-column label="计划开工时间" align="center" prop="scheduledStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scheduledStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划完工时间" align="center" prop="pctime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pctime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划数量" align="center" prop="plannedQuantity" />
      <el-table-column label="已包装数量" align="center" prop="quantityPacked" />
      <el-table-column label="已包装未入库数量" align="center" prop="quantityPackedNostored" />
      <el-table-column label="已入库数量" align="center" prop="quantityStorage" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="审核状态" align="center" prop="audit">
        <template #default="{ row }">
          <el-tag v-if="row.audit == 0" type="danger">未审核</el-tag>
          <el-tag v-if="row.audit == 2" type="success">已审核</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="结案状态" align="center" prop="close">
        <template #default="{ row }">
          <el-tag v-if="row.close == 0" type="danger">未结案</el-tag>
          <el-tag v-if="row.close == 2" type="success">已结案</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['storage:tickets:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改生产工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入订单号" />
        </el-form-item>
        <CustomSearch ref="ClientSelect1" label="客户" prop="clientName" labelWidth="110px" :tableKeys="ClientTableKeys1"
          formTitle="选择客户" primaryKey="clientName" showField="clientName" @getSearchList="getlistClient1"
          @updateQueryParams="updateQueryParamsForClient1" @selectDialogItem="selectDialogItemForClient1">
        </CustomSearch>
        <el-form-item label="客户名称" prop="clientName">
          <el-input v-model="form.clientName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="客户订单号" prop="clientOrderNumber">
          <el-input v-model="form.clientOrderNumber" placeholder="请输入客户订单号" />
        </el-form-item>
        <el-form-item label="客户下单日期" prop="clinentOrderDate">
          <el-date-picker clearable v-model="form.clinentOrderDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择客户下单日期">
          </el-date-picker>
        </el-form-item>
        <CustomSearch ref="ProductSelect1" label="产品" prop="productId" labelWidth="110px" :tableKeys="ProductTableKeys1"
          formTitle="选择产品" primaryKey="productId" showField="productName" @getSearchList="getlistProduct1"
          @updateQueryParams="updateQueryParamsForProduct1" @selectDialogItem="selectDialogItemForProduct1">
        </CustomSearch>
        <el-form-item label="产品编号" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入产品编号" />
        </el-form-item>
        <el-form-item label="颜色" prop="colour">
          <el-select v-model="form.colour" filterable placeholder="请选择颜色">
            <el-option v-for="dict in dict.type.colour" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <CustomSearch ref="WareHouseSearch2" label="默认仓库" prop="warehouseId" labelWidth="110px"
          :tableKeys="wareHouseTableKeys2" formTitle="选择仓库" primaryKey="warehouseId" showField="warehouseName"
          @getSearchList="getWareHouseSearchList2" @updateQueryParams="updateQueryParamsForWareHouse2"
          @selectDialogItem="selectDialogItemForWareHouse2"></CustomSearch>
        <el-form-item label="仓库" prop="warehouseId">
          <el-input v-model="form.warehouseId" placeholder="请输入仓库" />
        </el-form-item>
        <el-form-item label="计划开工/完工时间">
          <el-date-picker v-model="value1" type="daterange" range-separator="至" start-placeholder="计划开工时间"
            end-placeholder="计划完工时间" v-if="this.form" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划数量" prop="plannedQuantity" :rules="[
          { required: true, message: '计划数量不能为空' }
        ]">
          <el-input v-model.number="form.plannedQuantity" type="number" placeholder="请输入计划数量" autocomplete="off"
            @blur="handleValueplannedQuantity" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 打印生产工单的车辆ID -->
    <el-dialog title="生成/打印车辆ID" :visible.sync="dialogFormVisible">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="订单编号">
          <el-input v-model="form.ticketsId" placeholder="订单编号" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="计划数量">
          <el-input v-model="form.plannedQuantity" placeholder="计划数量" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="未打印数量">
          <el-input v-model="UnPrintNumber" placeholder="未计划数量" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="打印数量">
          <el-input v-model.number="PrintNumber" type="number" placeholder="打印数量" min="0" @blur="handleValue"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="Ongenerate" :disabled="ongenerate">生成车辆ID</el-button>
          <el-button type="primary" v-print="print" :disabled="printle" @click="printa">打印车辆ID</el-button>
          <el-button type="primary" @click="dialogFormVisibleClearing = true"
            :disabled="handpatching">手工补录车辆ID</el-button>
        </el-form-item>
      </el-form>
      <template>
        <el-table :data="tableData" height="250" border style="width: 100%" @selection-change="onChange">
          <el-table-column type="selection" ref='qrcode' width="55">
          </el-table-column>
          <el-table-column prop="bicycleId" label="车辆ID" width="180">
          </el-table-column>
          <el-table-column prop="orderId" label="工单号" width="180">
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.status" :value="scope.row.status" />
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="turngeneratecancel()">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配产品线 -->
    <el-dialog title="分配产品线" :visible.sync="productLineFormVisible">
      <el-form :model="form">
        <el-form-item label="产品线" prop="productLine">
          <el-select v-model="form.productLine" placeholder="请选择产品线">
            <el-option v-for="dict in dict.type.product_line" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="productLineFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="distribution">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 手工补录车辆ID -->
    <el-dialog title="手工补录车辆ID" :visible.sync="dialogFormVisibleClearing">
      <el-form :model="form">
        <el-form-item label="订单编号" label-width="100px">
          <el-input v-model="form.ticketsId" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="车辆ID" label-width="100px">
          <el-input v-model="form.bicycleId" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleClearing = false">取 消</el-button>
        <el-button type="primary" v-print="print" @click="Clearing">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 打印车辆ID页面 -->
    <div class="qrCode-container">
      <div id="printQrCode">
        <div v-for="(item, index) in this.printQrCode" :key="index" class="qrCode-content">
          <vue-qr ref="qrCode" :text="item.bicycleId"> </vue-qr>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { wareHouseSelect2 } from '@/mixins/wareHouse/wareHouseSelectForForm.js'
import { ProductSelect1 } from '@/mixins/product/productSelectForForm.js'
import { ProductSelect2 } from '@/mixins/product/productSelectForQueryParams.js'
import { ClientSelect1 } from '@/mixins/client/cliemtSelectForForm.js'
import { ClientSelect2 } from '@/mixins/client/cliemtSelectForQueryParams.js'
import { listTickets, getTickets, delTickets, addTickets, updateTickets, updateAudit, insertBicycle, updateClose, getBicycleUnPrintNumber, addBicycleByTicketsId, getBicycle, updateTicketsByproductLine } from "@/api/storage/tickets/tickets";
import { prints } from "@/api/storage/controller/bicycle";
import CustomSearch from "@/views/commons/CustomSearch.vue";
import { Message } from "element-ui";
import print from 'vue-print-nb'
import VueQr from 'vue-qr'
export default {
  name: "Tickets",
  components: { CustomSearch, VueQr },
  mixins: [wareHouseSelect2, ProductSelect1, ProductSelect2, ClientSelect1, ClientSelect2],
  dicts: ['colour', 'product_line', 'close', 'audit', 'customer_model', 'carton_size', 'specification_and_model', 'status'],
  directives: {
    print
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      //是否弹出打印车辆ID页面
      dialogFormVisible: false,
      // 是否弹出产品线分配
      productLineFormVisible: false,
      //手工补录页面
      dialogFormVisibleClearing: false,
      //限制车辆ID打印
      ongenerate: true,
      //限制手工补车辆ID打印
      handpatching: false,
      //车俩列表ID
      tableData: [],
      multipleSelection: [],
      // 选中数组
      ids: [],
      //选择车辆ID
      bicycleIds: [],
      //测试时间
      value1: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产工单表格数据
      ticketsList: [],
      //禁用打印
      printle: true,
      //打印的数目
      PrintNumber: 0,
      //未打印数目
      UnPrintNumber: "",
      // 弹出层标题
      title: "",
      //打印车辆ID页面选择
      printQrCode: "",
      // 是否显示弹出层
      open: false,
      // v-print除了绑定对应打印区域的id外，还可以绑定一个配置对象。
      print: {
        id: 'printQrCode',
        popTitle: '配置页眉标题', // 打印配置页上方的标题
        // 查看是否添加需求对打印进行优化
        // preview: false, // 是否启动预览模式，默认是false
        // previewTitle: '预览的标题', // 打印预览的标题
        // previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
        // zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
        // openCallback() {
        //   this.daying=true
        // }, // 调用打印时的callback
        // closeCallback() { console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        billData: null,
        clientName: null,
        clientOrderNumber: null,
        clinentOrderDate: null,
        colour: null,
        warehouseId: null,
        scheduledStartTime: null,
        pctime: null,
        audit: null,
        close: null,
        productId: null,
        productName: null,
        specifications: null,
        customerModel: null,
        cartonSize: null
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        warehouseId: [
          { required: true, message: "默认仓库不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "产品不能为空", trigger: "blur" }
        ],
        colour: [
          { required: true, message: "颜色不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //打印车辆ID
    printa() {
      prints(this.bicycleIds)
      this.$nextTick(function () {
        getBicycle(this.form.ticketsId).then(response => {
          this.tableData = response.data
        });
      })

    },
    //选择确定数据
    onChange(val) {
      this.bicycleIds = val.map(item => item.bicycleId)
      this.printQrCode = val
      this.printle = !val.length
    },
    /** 验证打印数量 */
    handleValue() {
      this.PrintNumber = parseInt(this.PrintNumber)
      if (this.PrintNumber < 0 || this.PrintNumber > this.UnPrintNumber) {
        this.PrintNumber = 0
      }
      this.ongenerate = false
      if (!(this.PrintNumber >= 0)) {
        this.ongenerate = true
      }
    },
    //验证计划数量
    handleValueplannedQuantity() {
      this.form.plannedQuantity = parseInt(this.form.plannedQuantity)
      if (this.form.plannedQuantity <= 0) {
        this.form.plannedQuantity = 1
      }
    },
    //补打车辆ID
    Clearing() {

      let str = [{
        bicycleId: this.form.bicycleId
      }]
      this.printQrCode = str

      insertBicycle(this.form);
      this.$modal.msgSuccess("打印成功")
      getBicycle(this.form.ticketsId).then(response => {
        this.tableData = response.data
      });
      prints(this.form.bicycleId)
      this.dialogFormVisibleClearing = false

    },
    /** 查询生产工单列表 */
    getList() {
      this.loading = true;
      listTickets(this.queryParams).then(response => {
        this.ticketsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //生成并打印车辆ID
    Ongenerate() {
      const data = {
        printnumber: this.PrintNumber,
        ticketsId: this.form.ticketsId
      }
      addBicycleByTicketsId(data);
      if (this.PrintNumber == 0) {
        Message.error("打印数量不为0")
        return
      }
      this.$modal.msgSuccess("已生成，等待打印")
      getBicycle(this.form.ticketsId).then(response => {
        this.tableData = response.data
      });
      this.UnPrintNumber = this.UnPrintNumber - this.PrintNumber
      this.PrintNumber = null;
      if (this.UnPrintNumber <= 0) {
        this.handpatching = true;
      }

    },
    //跳转打印车俩ID页面
    turngenerate() {
      const ticketsId = this.ids
      this.ongenerate = true;
      this.handpatching = false;
      getTickets(ticketsId).then(response => {
        if (response.data.audit == 0) {
          Message.error("该生产工单还未审核")
        } else {
          this.PrintNumber = null;
          this.reset();
          getTickets(ticketsId).then(response => {
            this.form = response.data;
            this.dialogFormVisible = true;
          });
          getBicycleUnPrintNumber(ticketsId).then(response => {
            this.UnPrintNumber = response.data
            if (this.UnPrintNumber <= 0) {
              this.handpatching = true;
            }
          });
          this.$nextTick(function () {
            getBicycle(ticketsId).then(response => {
              this.tableData = response.data
            });
          })

        }
      })
    },
    //打印车辆取消按钮
    turngeneratecancel() {
      this.dialogFormVisible = false
      this.PrintNumber = null;
      this.resetId();
    },
    //产品线分配界面distribution
    distributionInfo() {
      this.reset()
      this.productLineFormVisible = true
    },
    // 产品线分配
    distribution(row) {
      const ticketsIds = row.ticketsId || this.ids
      const productLine = {
        ticketsIds: ticketsIds,
        productLine: this.form.productLine
      }
      updateTicketsByproductLine(productLine)
      this.getList()
      this.$modal.msgSuccess("分配成功")
      this.productLineFormVisible = false
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //打印车辆ID重置
    resetId() {
      this.tableData = {
        bicycleId: null,
        orderId: null
      }
    },
    // 表单重置
    reset() {
      this.form = {
        ticketsId: null,
        orderNumber: null,
        billData: null,
        clientName: null,
        clientOrderNumber: null,
        clinentOrderDate: null,
        colour: null,
        warehouseId: null,
        productLine: null,
        scheduledStartTime: null,
        pctime: null,
        plannedQuantity: null,
        quantityPacked: null,
        quantityPackedNostored: null,
        quantityStorage: null,
        remark: null,
        audit: null,
        close: null,
        delFlag: null,
        productId: null,
        productName: null,
        specifications: null,
        customerModel: null,
        cartonSize: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ticketsId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ticketsId = row.ticketsId || this.ids
      getTickets(ticketsId).then(response => {
        this.form = response.data;
        this.value1[0] = response.data.scheduledStartTime;
        this.value1[1] = response.data.pctime;
        console.log(this.value1);
        this.open = true;
        this.title = "修改生产工单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //修改时间
          this.form.scheduledStartTime = this.value1[0]
          this.form.pctime = this.value1[1]
          if (this.form.ticketsId != null) {

            updateTickets(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log(this.form);
            addTickets(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ticketsIds = row.ticketsId || this.ids;
      this.$modal.confirm('是否确认删除生产工单编号为"' + ticketsIds + '"的数据项？').then(function () {
        return delTickets(ticketsIds).then(response => {
          if (!response.code == 200) {
            this.$modal.msgerror(response.msg)
          }
        })
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { });
    },

    /** 审核操作 */
    handleAudit(row) {
      this.reset();
      const ticketsId = row.ticketsId || this.ids;
      getTickets(ticketsId).then(response => {
        if (response.data.audit == 2) {
          this.$modal.confirm('是否确认反审核生产工单编号为"' + ticketsId + '"的工单').then(function () {
            return updateAudit(ticketsId);
          }).then(() => {
            this.getList();
            getTickets(ticketsId).then(response => {
              if (response.data.audit == 2) {
                Message.error("反审核失败，已经有后续的入库")
              } else {
                this.$modal.msgSuccess("反审核成功");
              }
            });

          }).catch(() => { });
        } else {
          this.$modal.confirm('是否确认审核生产工单编号为"' + ticketsId + '"的工单').then(function () {
            return updateAudit(ticketsId);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("审核成功");
          }).catch(() => { });
        }
      });



    },
    /** 结案操作 */
    handleClose(row) {
      const ticketsId = row.ticketsId || this.ids;
      getTickets(ticketsId).then(response => {
        if (response.data.close == 2) {
          this.$modal.confirm('是否确认反结案生产工单编号为"' + ticketsId + '"的工单').then(function () {
            return updateClose(ticketsId);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("反结案成功");
          }).catch(() => { });
        } else {
          this.$modal.confirm('是否确认结案生产工单编号为"' + ticketsId + '"的工单').then(function () {
            return updateClose(ticketsId);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("结案成功");
          }).catch(() => { });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('storage/tickets/export', {
        ...this.queryParams
      }, `tickets_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
